﻿using Infrastructure.Attribute;
using ZR.Service;
using ZR.ServiceCore.Model;
using ZR.ServiceCore.Model.Dto;
using ZR.ServiceCore.Services.IService;

namespace ZR.ServiceCore.Services;
[AppService(ServiceType = typeof(ISysRoleFieldService), ServiceLifetime = LifeTime.Transient)]
public class SysRoleFieldService : BaseService<SysRoleField>, ISysRoleFieldService
{
    public async Task<bool> InsertOrUpdateSysRoleField(List<SysFieldDto> sysFieldDtos, long roleId)
    {
        try
        {
            await Context.Ado.BeginTranAsync();
            await Deleteable()
                .Where(it => it.RoleId == roleId)
                .Where(it => sysFieldDtos.Select(sf => sf.Id).ToArray()
                    .Contains(it.FieldId))
                .ExecuteCommandAsync();
            var ids = sysFieldDtos
                .Where(it => it.IsPermission != true)
                .Select(it => new SysRoleField
                {
                    FieldId = it.Id,
                    RoleId = roleId
                })
                .ToList();
            await Insertable(ids).ExecuteCommandAsync();
            await Context.Ado.CommitTranAsync();
            return true;
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            await Context.Ado.RollbackTranAsync();
            throw;
        }
        // var list = await
        //     Queryable()
        //     .LeftJoin<SysField>((rf, f) => rf.FieldId == f.Id)
        //     .Where((rf, f) => rf.RoleId == roleId && f.FullName == sysFieldDtos[0].FullName)
        //     .ToListAsync();
        //
        //
        // list.AddRange(ids);
        // list = list.Distinct().ToList();
        // var sysRoleFieldStore = await
        //     Storageable(ids)
        //     .WhereColumns(it => new { it.FieldId, it.RoleId })
        //     .ToStorageAsync();
        // await sysRoleFieldStore.AsInsertable.ExecuteCommandAsync();
        // await sysRoleFieldStore.AsUpdateable.ExecuteCommandAsync();
        // await sysRoleFieldStore.AsDeleteable.ExecuteCommandAsync();
        // return true;
    }
}